package cn.ecpay.unionpay.settle.controller;

import cn.ecpay.unionpay.settle.Common.CommonUtil;
import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.Common.RespCode;
import cn.ecpay.unionpay.settle.Common.UnionpayDict;
import cn.ecpay.unionpay.settle.dao.QuotaIncreaseDao;
import cn.ecpay.unionpay.settle.entity.db.TPvQuotaIncrease;
import cn.ecpay.unionpay.settle.entity.db.TPvRealTimeBalanceQuery;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import cn.ecpay.unionpay.settle.util.SDKConfig;
import org.rex.db.exception.DBException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 额度调增
 * Created by zhaoyanzeng on 2018/11/6.
 */
@RestController
public class QuotaIncreaseController {

    @Resource
    private QuotaIncreaseDao quotaIncreaseDao;

    @RequestMapping(value = "/quotaIncrease", method = RequestMethod.POST)
    protected String quotaIncrease(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Map<String, String> contentData = convertContentData(req);
        if(isExistTxn(contentData.get("txnNo"),contentData.get("txnDate"))){
            return "重复交易";
        }
        TPvQuotaIncrease quotaIncrease = new TPvQuotaIncrease();
        /**对请求参数进行签名并发送http post请求，接收同步应答报文**/
        Map<String, String> reqData = FsasService.sign(contentData, CommonBase.encoding);			//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        reqDataConvert(quotaIncrease,reqData);
        String requestBackUrl = SDKConfig.getConfig().getBackRequestUrl();   			//交易请求url从配置文件读取对应属性文件fsas_sdk.properties中的 fsassdk.backTransUrl
        Map<String, String> rspData = FsasService.doPost(reqData,requestBackUrl, CommonBase.encoding); //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过
        rspDataConvert(quotaIncrease,rspData);
        StringBuffer parseStr = new StringBuffer("");
        if(!rspData.isEmpty()){
            if(FsasService.validate(rspData, CommonBase.encoding)){
                LogUtil.writeLog("验证签名成功");
                quotaIncrease.setRespValidate("1");
                String respCode = rspData.get("respCode") ;
                if(RespCode.RESP_SUCCESS.equals(respCode)){
                    //成功
                    //TODO
                }else{
                    //其他应答码为失败请排查原因
                    //TODO
                }
            }else{
                LogUtil.writeErrorLog("验证签名失败");
                quotaIncrease.setRespValidate("0");
                //TODO 检查验证签名失败的原因
            }
        }else{
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
        }
        try {
            quotaIncreaseDao.insert(quotaIncrease);
        } catch (DBException e) {
            LogUtil.writeErrorLog("保存额度调增失败");
            e.printStackTrace();
        }
        String reqMessage = CommonBase.genHtmlResult(reqData);
        String rspMessage = CommonBase.genHtmlResult(rspData);
        return "额度调增请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+parseStr;
    }



    private Map<String, String> convertContentData(HttpServletRequest req) {
        String acqInsCode = req.getParameter("acqInsCode");
        String txnNo = req.getParameter("txnNo");
        String txnDate = req.getParameter("txnDate");
        String txnAmt = req.getParameter("txnAmt");

        Map<String, String> contentData = new HashMap<String, String>();
        /***银联资金结算接入系统，产品参数，除了encoding自行选择外其他不需修改***/
        contentData.put("version", CommonBase.version);                  //版本号
        contentData.put("encoding", CommonBase.encoding);             //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", UnionpayDict.TXN_TYPE_QUOTAINCREASE);                                   //交易类型 52 额度调增模式一、 53 额度调增模式二
        contentData.put("txnAmt", txnAmt);                                    //调整额度
        contentData.put("currencyCode", "156");                                    //币种
        contentData.put("acqInsCode", acqInsCode);                        //机构代码
        contentData.put("txnNo", txnNo);                                    //交易流水号
        contentData.put("txnDate",txnDate);                               //交易日期
        contentData.put("sndTime", CommonBase.getSendTime());      //发送时间 格式HHmmss
//         contentData.put("backUrl", CommonBase.backUrl);        //后台通知地址
        return contentData;
    }

    //申请参数
    private void reqDataConvert(TPvQuotaIncrease quotaIncrease, Map<String, String> reqData) {
        quotaIncrease.setTxnNo(reqData.get("txnNo"));
        quotaIncrease.setAcqInsCode(reqData.get("acqInsCode"));
        quotaIncrease.setTxnType(reqData.get("txnType"));
        quotaIncrease.setTxnDate(reqData.get("txnDate"));
        quotaIncrease.setSndTime(reqData.get("sndTime"));
        quotaIncrease.setCurrencyCode(reqData.get("currencyCode"));
        quotaIncrease.setTxnAmt(reqData.get("txnAmt"));
        quotaIncrease.setCreateTime(DateUtil.getDateTo19(new Date()));
    }

    //同步返回结果
    private void rspDataConvert(TPvQuotaIncrease quotaIncrease,Map<String, String> rspData) {
        quotaIncrease.setRespCode(rspData.get("respCode"));
        quotaIncrease.setRespMsg(rspData.get("respMsg"));
    }

    /**
     * 交易是否已存在
     *
     * @return
     */
    public boolean isExistTxn(String txnNo, String txnDate) {
        try {
            return quotaIncreaseDao.isExistTxn(txnNo, txnDate);
        } catch (DBException e) {
            e.printStackTrace();
            return false;
        }
    }
}
